#!/usr/bin/python3
#-- coding:utf-8 --

import xmltodict
import types
from collections import OrderedDict

with open('running-config.xml', 'r') as f:
    str_xml = str(f.read())

str_xml = str_xml.replace('&', '&#38;')  # xml格式不能有"&"符号
doc = xmltodict.parse(str_xml)

configObj = doc["Config"]

headerObj = configObj["Header"]
mibDatasObj = configObj["MibData"]
footerObj = configObj["Footer"]

mibList = mibDatasObj["MIB"]


def handleAttributeTag(attrObj):
    if (type(attrObj) == list):
        for v in attrObj:
            handleAttributeTag(v)
    else:
        print("====================Attribute Start====================")
        print(attrObj["@name"])  #Attribute中的name字段
        print(attrObj.get("@convert"))  #Attribute中的convert字段
        print(attrObj.get("#text"))  #<Attribute></Attribute>中间夹的文本
        print("====================Attribute End====================")


for k in mibList:  #循环Tag是MIB的列表
    for mibk, mibv in k.items():
        if (mibk == "Table"):
            tabList = k["Table"]
            for t in tabList:  #操作Tag:MIB下Tag:Table的列表
                if (type(t) == OrderedDict):
                    for tk, tv in t.items():
                        if (
                                tk == "Entry"
                        ):  #Entry下面会有多条Attribute，一条Attribute时是Attribute的对象，多条时候是一个Attribute对象的列表
                            if (type(tv) == list):
                                for tve in tv:
                                    if (tve["Attribute"] != None):
                                        for tvea in tve["Attribute"]:
                                            handleAttributeTag(tvea)
                            else:
                                handleAttributeTag(tv["Attribute"])
        elif (mibk == "Scalar"):  #操作Tag:MIB下Tag:Scalar的列表
            scalarList = k["Scalar"]
            for s in scalarList:
                if (type(s) == OrderedDict):
                    for sk, sv in s.items(
                    ):  #Scalar下会有多条Attribute，一条Attribute时是Attribute的对象，多条时候是一个Attribute对象的列表
                        if (sk == "Attribute"):
                            handleAttributeTag(sv)
